// ==UserScript==
// @name           Gegtik's Dinosaur Comics
// @namespace      http://www.lmnopc.com/greasemonkey/
// @description    Turns gegtik's posts into hilarious Dinosaur Comics! 
// @include        http://shacknews.com/*
// @include        http://*.shacknews.com/*
// ==/UserScript==

/* 
	05-19-2009
		- Initial release
	05-20-2009
		- Added TroZ's font resizing code.  Sweet!
	05-20-2009 Noon
		- Fixed URL parsing so it deals with links that have newlines in them

*/ 

if ((script_enabled('gegtiks_dinosaur_comics') == "true") && (location.href.indexOf('laryn.x') != -1))  
{

// I found that I had to sandbox this script or it would kill the DHTML 
// that makes the dynamic post loading work.  I'm thinking one of my function 
// names is the same as a necessary Shack function name? 

(function() {

    var benchmarkTimer = null;
    var scriptStartTime = getTime();
    function getTime() { benchmarkTimer = new Date(); return benchmarkTimer.getTime(); }

	function stripHtml(html) { return String(html).replace(/(<([^>]+)>)/ig, ''); }
	
    function getElementByClassName(oElm, strTagName, strClassName) 
	 {
        var arrElements = oElm.getElementsByTagName(strTagName);
        for (var i = 0; i < arrElements.length; i++) 
		  {
            if (arrElements[i].className.indexOf(strClassName) == 0) 
				{
                return arrElements[i];
            }
        }
    }

	function parsePost(post)
	{
		var res = new Array(); 
	
		// Extract all the links, store them in links[] and replace the link with a %%link%% placeholder in the post 
		var links = new Array(); 
		var regExLink = new RegExp(/<a.*? href=(\"|')(.*?)([\n|\r]*?)(\"|').*?>(.*?)([\n|\r]*?)<\/a>/i);
		do 
		{
			var m = regExLink.exec(post);
			if (m == null) 
			{
				break;
			}
			links.push(m[0]); 
			post = post.replace(regExLink, '%%link%%'); 
		}
		while (1)
	
		// Strip HTML from the post 	
		post = stripHtml(post);
		
		// Split paragraphs
		var lines = post.split('\n');
		
		// Get sentences from paragraphs
		for (var i = 0; i < lines.length; i++)
		{
			lines[i] = lines[i].replace('...', '&Ellipsis;'); 
	
			var sentences = lines[i].split('.');
			
			for (var j = 0; j < sentences.length; j++)
			{
				if (sentences[j].length)
				{
					var tmp = sentences[j];
					tmp = tmp.replace('&Ellipsis;', '...'); 
	
					// replace %%link%% placeholders with actual links
					while (tmp.indexOf('%%link%%') > -1)
					{
						tmp = tmp.replace(/%%link%%/i, links.shift());
					}
	
					res.push(tmp);
				}
			}
		}
		return res; 
	}
	
	function frame(x, y, width, height, lines)
	{
		this.x = x; 
		this.y = y; 
		this.width = width; 
		this.height = height; 
		this.lines = lines;
	}
	
	var frames = new Array(
		new frame(5, 5, 234, 92, 7),
		new frame(248, 5, 121, 92, 7), 
		new frame(517, 5, 214, 150, 11), 
		new frame(4, 246, 186, 67, 5), 
		new frame(198, 246, 291, 66, 5), 
		new frame(496, 246, 234, 56, 4)
	);
	
	function processPost(id)
	{
		var comicId = 'dinosaurComic_' + id; 
	
		// Prevent duplicate comics
		if (document.getElementById(comicId))
		{
			return; 
		}
		
		var item = document.getElementById(id); 
		
		var thePost = getElementByClassName(item, 'div', 'postbody'); 
		
		if (typeof(thePost) == 'undefined')
		{
			return;
		}
	
		var text = parsePost(thePost.innerHTML); 
		
		// Create Dinosaur Comic container
		var div = doc.createElement('div');
		div.id = comicId; 
		div.className = 'dinosaurComic';
		// CSS moved to shackscripts.css 
		div.style.height = (text.length <= 3) ? '244px' : '487px';
		
		thePost.appendChild(div); 
		
		// Populate frames
		var iMax = (text.length < frames.length) ? text.length : frames.length; 
		
		for (var i = 0; i < iMax; i++)
		{	
			var f = doc.createElement('div');
			
			f.style.position = 'absolute'; 
			f.style.display = 'block';
			
			f.style.left = frames[i].x + 'px'; 
			f.style.top = frames[i].y + 'px'; 
			f.style.width = frames[i].width + 'px'; 
			f.style.height = frames[i].height + 'px'; 
			f.style.overflow = 'hidden'; 
			f.style.lineHeight = '1em';
			
			f.innerHTML = text[i]; 
			
			div.appendChild(f);  
	
			//resize font code
			var size=12;
			while((f.scrollHeight > f.clientHeight) && (size>7))
			{
				f.style.fontSize = ''+size+'px';
				
				size--;
			}	
		}
	}
	
	// 
	function main() 
	{
		var gegtikPosts = top.document.evaluate("//div[contains(@class,'fpauthor_174527')]/..",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
		for (var i = 0; i < gegtikPosts.snapshotLength; i++) 
		{
			// Find the item id 
			processPost(gegtikPosts.snapshotItem(i).id);
		}
	}

	// Install javascript replacement function	
	if ((typeof(gegtik_show_item_fullpost) == 'undefined') && (typeof(show_item_fullpost) != 'undefined')) 
	{
	   gegtik_show_item_fullpost = show_item_fullpost;
	   show_item_fullpost = function(root_id, article_id, fullpost_element) 
		{
			gegtik_show_item_fullpost(root_id, article_id, fullpost_element);
			
			var id = 'item_' + article_id; 

			// Make sure gegtik wrote this post
			if (document.getElementById(id).getElementsByTagName('div')[0].className.indexOf('fpauthor_174527') != -1)
			{
				processPost(id);
			}
	   }
	}
	
	// 
	main(); 
	
	// Install event handler on iframe 
	document.getElementById('dom_iframe').addEventListener('load', function() { setTimeout(main, 100); } , false); 

	// Log execution time 
	GM_log('gegtiks_dinosaur_comics.js: ' + (getTime() - scriptStartTime) + 'ms');

})();

}
